package elven.d.rabbitmq.server.util;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import org.apache.commons.lang3.SerializationUtils;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

import elven.d.common.log.LogFactory;

/**
 * 消费者,读取队列的程序端,实现Runable接口
 * @author elven
 */
public class QueueConsumer extends EndPoint implements Runnable, Consumer {

	public QueueConsumer(String endPointName) throws TimeoutException, IOException {
		super(endPointName);
	}
	
	@Override
	public void run() {
		try {
			channel.basicConsume(endPointName, true, this);
		} catch (IOException e) {
			LogFactory.d().error(e.getMessage(), e);
		}
	}
	
	/* 
	 * rabbitMQ接收消息
	 * @see com.rabbitmq.client.Consumer#handleDelivery(java.lang.String, com.rabbitmq.client.Envelope, com.rabbitmq.client.AMQP.BasicProperties, byte[])
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void handleDelivery(String consumerTag, Envelope enve, BasicProperties props, byte[] body) throws IOException {
		 String datas = SerializationUtils.deserialize(body);
		 LogFactory.d().info("Message {} received", datas);
	}
	
	@Override
	public void handleConsumeOk(String consumerTag) {}

	@Override
	public void handleCancelOk(String consumerTag) {}

	@Override
	public void handleCancel(String consumerTag) throws IOException {}

	@Override
	public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {}

	@Override
	public void handleRecoverOk(String consumerTag) {}

}
